<?php


function encode_time($time) { return 9999999999 - $time; }
function decode_time($time) { return 9999999999 - $time; }

function note_time($time) { return date('d.m.Y H:i:s', $time); }

function is_whitespace($c) { return $c == ' ' || $c == "\n" || $c == "\r" || $c == "\t"; }

function tolower($c) { return ('A' <= $c && $c <= 'Z' ? $c - 'A' + 'a' : $c); }

function hash_password($password) {
    // TODO: invent something more clever?..
    return md5($password);
}


function augment_hrefs($s, &$placed_hrefs = false) {
    $n = strlen($s);
    $answer = "";
    for ($i = 0; $i < $n;) {
        if ($i + 7 <= $n && $s[$i] == 'h' && $s[$i + 1] == 't' &&
          (substr($s, $i, 7) == 'http://' || ($i + 8 <= $n && substr($s, $i, 8) == 'https://'))) {
            $j = $i + 7;
            while ($j < $n && !is_whitespace($s[$j])) $j++;
            $link = substr($s, $i, $j - $i);
            $str = '<a href="'.$link.'">'.$link.'</a>';
            if ($placed_hrefs !== false) {
                $len0 = strlen($answer);
                $len1 = $len0 + strlen('<a href="'.$link.'">');
                $len2 = $len1 + strlen($link);
                $len3 = $len2 + strlen('</a>');
                $placed_hrefs[] = array($len0, $len1, $len2, $len3);
            }
            $answer = $answer.$str;
            $i = $j;
        } else {
            $answer = $answer.$s[$i];
            $i++;
        }
    }
    return $answer;
}

function highlight_substring($s, $t, $placed_hrefs = array()) {
    $n = strlen($s);
    $m = strlen($t);
    $answer = "";
    $forbidden_substrings = array();
    foreach ($placed_hrefs as $l4) {
        $forbidden_substrings[$l4[0]] = $l4[1];
        $forbidden_substrings[$l4[2]] = $l4[3];
    }
    for ($i = 0; $i < $n;) {
        if (isset($forbidden_substrings[$i])) {
            $j = $forbidden_substrings[$i];
            while ($i < $n && $i < $j) {
                $answer = $answer.$s[$i];
                $i++;
            }
        }
        $ss = substr($s, $i, $m);
        if ($i + $m <= $n && !strcasecmp($ss, $t)) {
            $answer = $answer."<span class=\"hl\">".$ss."</span>";
            $i += $m;
        } else if ($i < $n) {
            $answer = $answer.$s[$i];
            $i++;
        }
    }
    return $answer;
}

function highlight_substring_augmenting_hrefs($s, $t) {
    $placed_hrefs = array();
    $augmented = augment_hrefs($s, $placed_hrefs);
    return highlight_substring($augmented, $t, $placed_hrefs);
}


?>
